package com.baizhi.util;

import com.baizhi.dao.CmfzAdminDao;
import com.baizhi.entity.CmfzAdmin;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author: renpu
 * @Date: 2019/3/14 19:20
 * @Description:
 */
public class DataResourceRealm extends AuthenticatingRealm {
    @Autowired
    private CmfzAdminDao cmfzAdminDao;
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {




        //在Spring框架中获取session的方法；
        ServletRequestAttributes rr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = rr.getRequest();
         HttpSession session = request.getSession();

        //接受用户所输入得数据；
        String userName = (String) token.getPrincipal();

        //调用方法从数据库进行查询；
        CmfzAdmin cmfzAdmin = cmfzAdminDao.selectOneT(userName);


        //存储在session里；
        session.setAttribute("user",cmfzAdmin);

        //交给SimpleAuthenticationInfo对象，所需要的参数实体类get方法获取到的用户名称以用户的密码，当前对象的getName()方法；
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(cmfzAdmin.getUserName(),cmfzAdmin.getPassWord(),this.getName());

        //判断通过shiro框架的校验封装到info里面；
        if(info!=null){
            return info;
        }
        return null;
    }
}
